<template>
    <div class="container">
        <div class="orderSuccess">
            <div class="orderSuccess_text">
                <div class="complete" @click="goToHome()">完成</div>
                <div class="success_message">
                    <uni-icons type="checkbox-filled" size="30" color="#37B133"></uni-icons>
                    <div style="margin-left:2%">
                        购买成功
                    </div>
                </div>
                <div class="payment-amount">实付:<span style="color:rgba(255, 141, 26, 1)">￥{{ order_total_price }}</span>
                </div>
                <div class="action-buttons">
                    <button class="view-order" @click="goToOrderDetail()">查看订单</button>
                    <button class="continue-shopping" @click="goToFood()">继续逛逛</button>
                </div>
            </div>
        </div>
        <div class="reminder">
            防诈骗提醒:我们不会以任何理由发送链接要求您填
            写个人银行信息进行款项操作。谨防欺诈风险!
        </div>

        <div class="guess">
            猜你还想要
        </div>

        <!-- 商品列表区域 -->
        <div class="product_list">
            <div class="product_item" v-for="(item, index) in products_shop" :key="index" @click="goDetail(item)">
                <image :src="getFullImageUrl(item.img)" mode="aspectFill"
                    style="width: 100%; height: 150px; border-radius: 5px;">
                </image>
                <div class="product_title">{{ item.title }}</div>
                <div class="product_price">{{ item.synopsis || item.notice }}</div>

                <div class="product_notice">
                    <div class="notice">{{ item.notice || '暂无描述' }}</div>
                    <div class="sales">销售量{{ item.quantity }}</div>
                </div>

                <div class="product_info">
                    <div class="score">￥{{ item.price || '0.00' }}</div>
                    <div class="sales" style="text-decoration: line-through;">￥{{ item.money || '0.00' }}</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
// ========== 引用依赖 ==========
import { ref } from 'vue'
import { onShow } from "@dcloudio/uni-app";
import { foodAPI } from '../../static/indexAPI.js'
import config from '../../static/config.js';

// ========== 声明响应式变量 ==========
const state_shop = ref({});
const products_shop = ref([]);

// ========== 声明普通变量 ==========
const order_total_price = uni.getStorageSync('order_total_price') || 0;
let shopID = uni.getStorageSync('shopID') || 0;
const baseUrl = config.baseURL; // 使用默认baseURL

// 如果shopID为空，尝试从商品信息中获取
if (!shopID) {
  const selectedProduct = uni.getStorageSync('selectedProduct');
  if (selectedProduct && selectedProduct.foodshop_id) {
    shopID = selectedProduct.foodshop_id;
  }
}

// ========== 工具函数 ==========
/**
 * 获取完整的图片URL，确保不会有重复的基础URL前缀
 * @param {string} imgUrl - 原始图片URL
 * @returns {string} 完整的图片URL
 */
const getFullImageUrl = (imgUrl) => {
    if (!imgUrl) return '';

    // 如果已经是完整URL（以http://或https://开头），直接返回
    if (/^https?:\/\//i.test(imgUrl)) {
        return imgUrl;
    }

    // 处理相对路径（以/开头）
    if (imgUrl.startsWith('/')) {
        return baseUrl + imgUrl;
    }

    // 其他情况（没有/开头），添加baseUrl和/
    return baseUrl + '/' + imgUrl;
};

// ========== 网络请求 ==========
/**
 * 获取店铺详情
 */
const fetchShopDetail = () => {
    
    if (!shopID) {
        console.error('shopID为空，无法请求店铺详情');
        return;
    }
    
    // 使用封装好的API接口
    return foodAPI.getShopDetail({ id: shopID }).then((res) => {
        
        if (res.data && res.data.code === 1 && res.data.data) {
            state_shop.value = res.data.data;
            
            // 检查是否有商品数据
            if (res.data.data.product && Array.isArray(res.data.data.product)) {
                // 过滤掉当前购买的商品，只显示其他商品
                const purchasedProductId = uni.getStorageSync('currentProductId');
                let products = res.data.data.product;
                
                
                if (purchasedProductId) {
                    products = products.filter(product => product.id != purchasedProductId);
                }
                
                // 处理商品数据，确保字段正确
                products_shop.value = products.map(item => {
                    return {
                        ...item,
                        img: item.img ? getFullImageUrl(item.img) : '',
                        // 确保数值字段是正确的类型
                        price: parseFloat(item.price) || 0,
                        money: parseFloat(item.money) || 0,
                        quantity: parseInt(item.quantity) || 0
                    };
                });
                
            } else {
                products_shop.value = [];
            }
        } else {
        }
    }).catch((err) => {
        console.error('获取店铺详情失败:', err);
    });
};

// ========== 页面导航功能 ==========
/**
 * 跳转到商品详情
 */
const goDetail = (item) => {
    uni.navigateTo({
        url: `/pages/foodDetail/foodDetail?id=${item.id}`
    });
};

/**
 * 返回首页
 */
const goToHome = () => {
    uni.switchTab({
        url: '/pages/index/index'
    });
};

/**
 * 查看订单详情
 */
const goToOrderDetail = () => {
    uni.redirectTo({
        url: '/pages/order/order'
    });
};

const goToFood = () => {
    uni.switchTab({
        url: '/pages/index/index'
    });
};

// ========== 生命周期 ==========
onShow(() => {
    // 重新获取数据，确保是最新的
    const currentOrderTotalPrice = uni.getStorageSync('order_total_price') || 0;
    let currentShopID = uni.getStorageSync('shopID') || 0;
    
    // 如果shopID为空，尝试从商品信息中获取
    if (!currentShopID) {
      const selectedProduct = uni.getStorageSync('selectedProduct');
      if (selectedProduct && selectedProduct.foodshop_id) {
        currentShopID = selectedProduct.foodshop_id;
      }
    }
    
    fetchShopDetail();
});
</script>

<style lang="scss" scoped>
.success_img {
    width: 20px;
    height: 20px;
    margin-top: 1%;
}

.container {
    width: 100%;
    background-color: #f5f5f5;
    padding: 20px 0;
    height: 95vh;
}

.orderSuccess {
    width: 100%;
    max-width: 500px;
    height: 280px;
    background-color: white;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.orderSuccess_text {
    width: 90%;
    text-align: center;
    position: relative;
}

.complete {
    font-size: 14px;
    font-weight: bold;
    margin-top: 42px;
    position: absolute;
    right: 0;
    top: 0;
}

.success_message {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    margin-top: 70px;
    display: flex;
    justify-content: center;
}

.payment-amount {
    font-size: 16px;
    color: #666;
    margin-bottom: 40px;
}

.action-buttons {
    display: flex;
    justify-content: center;
    gap: 20px;
}

.view-order,
.continue-shopping {
    border-radius: 20px;
    font-size: 14px;
}

.view-order {
    border: 1px solid #000;
    background: white;
}

.continue-shopping {
    border: 1px solid #000;
}

.reminder {
    width: 92%;
    margin-left: 4%;
    text-indent: 12px;
    margin-top: 2%;
    color: rgba(150, 149, 149, 1);
    font-size: 14px;
}

.guess {
    width: 100%;
    height: 40px;
    font-size: 16px;
    line-height: 40px;
    text-indent: 20px;
    color: #222222;
    font-weight: bold;
    background-color: white;
    margin-top: 5%;
}

/* 商品列表区域样式 */
.product_list {
    width: 95%;
    box-sizing: border-box;
    column-count: 2;
    column-gap: 10px;
    margin: 0 auto;
    margin-top: 2%;
}

.product_item {
    break-inside: avoid;
    margin-bottom: 15px;
    background-color: #ffffff;
    border-radius: 8px;
    padding: 10px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.product_title {
    font-size: 14px;
    color: #333;
    margin: 8px 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.product_price {
    font-size: 12px;
    color: #999;
    font-weight: bold;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.product_info {
    width: 100%;
    height: 30px;
    display: flex;
    align-items: center;
    font-size: 12px;
    color: rgba(255, 141, 26, 1);
}

.product_notice {
    width: 100%;
    align-items: center;
    font-size: 12px;
    color: rgba(128, 128, 128, 1);
}

.score {
    width: auto;
}

.notice {
    width: 50%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.sales {
    color: #999;
    margin-left: auto;
}

.category_list {
    width: 90%;
    margin-top: 5%;
    margin-left: 5%;
}

.category_section {
    width: 64%;
}
</style>